<?php
namespace App\Http\Controllers\CRM;
use App\Order;
use App\Rad_user;
use App\Rad_user_account;
use Illuminate\Http\Request;

use App\Common\ErrorDefine;

use App\Radacct;
use App\Radcheck;
use App\Radgroupcheck;
use App\Radreply;
use App\Radusergroup;
use App\Rad_manage;
use App\Radgroupreply;
use App\Rad_users;
use App\Rad_account;
use App\Rad_merge_data;
use DB;
use App\Rad_manage_discount;
use App\Rad_order;
use App\Line;
use App\Agent;
use App\Teamqq;

use App\Manage_user_list;
use App\Discount;
use App\Http\Controllers\Controller;
use Redis;
use App\Terrace;
use App\Http\Controllers\CRM\PublicController;
use App\Http\Controllers\Radius\ModuleController;

class RemoveController extends Controller
{
    /**
     * @param Request $request
     * 删除子账号
     */
    public function doRemoveChildAccount(Request $request)
    {
        $public = new PublicController();
        $module = new ModuleController();
        if(!$request->has('token') && empty($request->input('token')))
        {
            self::ShowError(ErrorDefine::TOKEN_NOT_EXIST);
            return;
        }

        if(!$request->has('pid') && empty($request->input('pid')))
        {
            self::ShowError(ErrorDefine::INVALID_PID);
            return;
        }
        $pid = $request->input('pid');
        $token = $request->input('token');


        $user = $public->getTokenById($token);

        $manage_id = $user[0]['manage_id'];
        $level= $user[0]['level'];

        $id  = $request->input('id');

        $id = explode(',',$id);
        $num = count($id);

        foreach($id as $value)
        {

            $user = Radcheck::find($value);
            $ret =  Rad_users::find($value);

            if($ret != NULL)
            {
                //  删除用户表信息
                if($user != NULL)
                {
                    $ret = Radcheck::where('username',$user->username)->delete();
                    $ret1 = Radusergroup::where('username',$user->username)->delete();

                    $ret3 = Radreply::where('username',$user->username)->delete();
                    $ret4 = Manage_user_list::where('username',$user->username)->delete();
                }

                if($value == $pid)
                {
                   $users = Rad_users::find($pid);
                    $users->pid= 0;
                    $users->save();
                }else{
                    $ret2 = Rad_users::where('user_id',$value)->delete();

                }
            }

        }

        $users = Rad_users::find($pid);

            if( $users->account_num -$num >=0)
        {
            $users->account_num = $users->account_num -$num;
        }else{
            $users->account_num =  0;
        }

        $users->save();


        return self::ShowMessage('SUCCESS');
    }


}